<template>
    <div ref="auto" class="auto-parent">
        <Input
            @on-focus="onFocus"
            @input="onSearch"
            @on-enter="onEnter"
            class="large"
            :class="className" 
            v-model="currValue"
            :placeholder="placeholder"
            clearable 
            :maxlength="30"/>
        <div class="autocomplete" v-if="!custom">
            <div
                v-for="(item, i) in data"
                :key="i"
                @click="onSelect(item)"
                class="item">
                {{item}}
            </div>
        </div>
        <div class="autocomplete" v-else>
            <slot></slot>
        </div>
    </div>   
</template>

<script>
    export default {
        name: 'Suggestion',
        props: {
            placeholder: {
                type: String,
                default: '请输入',
                
            },
            value: {
                type: [String, Number],
                default: ''
            },
            data: {
                type: Array,
                default: []
            },
            className: {
                type: String,
                default: ''
            },
            custom: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                currValue: this.value
            }
        },
        mounted() {
            document.addEventListener('click', this.onDocumentClick);
        },
        destroyed() {
            document.removeEventListener('click', this.onDocumentClick);
        },
        methods: {
            onDocumentClick(e) {
                if (!this.$refs.auto.contains(e.target)) {
                    this.$emit('clear');
                }
            },
            onSearch() {
                this.$emit('input', this.currValue);
                this.$emit('searchBefore');
                this.$nextTick(() => this.$emit('search', this.currValue));
            },
            onFocus() {
                this.$emit('focus');
            },
            onSelect(item) {
                this.currValue = item;
                this.$emit('input', item);
                this.$nextTick(() => {
                    this.$emit('select', item);
                    this.$emit('clear');
                })
            },
            onEnter() {
                this.$emit('enter')
            }
        },
        watch: {
            currValue() {
                this.$emit('input', this.currValue);
            },
            value() {
                this.currValue = this.value;
            }
        }
    }
</script>

